package com.aba.im.ui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ChatClient {
    private static final String SERVER_IP = "127.0.0.1";
    private static final int SERVER_PORT = 8888;
    private Socket socket;
    private Scanner in;
    private PrintWriter out;
    private JFrame frame;
    private JTextField messageField;
    private JTextArea chatArea;

    public ChatClient() {
        try {
            socket = new Socket(SERVER_IP, SERVER_PORT);
            in = new Scanner(socket.getInputStream());
            out = new PrintWriter(socket.getOutputStream(), true);

            // 初始化Swing界面
            frame = new JFrame("聊天客户端");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 300);

            messageField = new JTextField();
            frame.add(messageField, java.awt.BorderLayout.SOUTH);

            chatArea = new JTextArea();
            frame.add(new javax.swing.JScrollPane(chatArea), java.awt.BorderLayout.CENTER);

            JButton sendButton = new JButton("发送");
            sendButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String message = messageField.getText();
                    if (!message.isEmpty()) {
                        // 假设私聊协议：MSG|发送者|接收者|消息内容
                        String receiver = JOptionPane.showInputDialog(frame, "请输入私聊对象用户名");
                        if (receiver != null) {
                            out.println("MSG|" + "your_username" + "|" + receiver + "|" + message);
                            chatArea.append("你对 " + receiver + " 说: " + message + "\n");
                            messageField.setText("");
                        }
                    }
                }
            });
            frame.add(sendButton, java.awt.BorderLayout.EAST);

            frame.setVisible(true);

            new Thread(() -> receiveMessages()).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void receiveMessages() {
        while (true) {
            if (in.hasNextLine()) {
                String message = in.nextLine();
                if (message.startsWith("PRIVATE_MSG|")) {
                    String[] parts = message.split("\\|");
                    String sender = parts[1];
                    String msgContent = parts[2];
                    chatArea.append(sender + " 私聊你: " + msgContent + "\n");
                }
            }
        }
    }

    public static void main(String[] args) {
        new ChatClient();
    }
}

